package dao.impl;

import bean.Goods;
import bean.CartItem;
import dao.BaseDao;
import dao.CartItemDao;

import java.util.List;

public class CartItemImpl extends BaseDao<CartItem> implements CartItemDao {
    @Override
    public int addbook(CartItem cartItem) {

        String sql = "select `item_id` as itemId from t_cart_item where `book_id` = ? and `user_id` = ?";
        List<CartItem> list = query(sql, cartItem.getBookId(), cartItem.getUserId());

        if (list.size() == 0) {
            sql = "insert into t_cart_item(`item_id`, `book_id`,`user_id`,`name`,`count`,`unit_price`)" +
                    " values(?,?,?,?,?,?)";

            return update(sql, cartItem.getItemId(), cartItem.getBookId(), cartItem.getUserId(), cartItem.getName(), cartItem.getCount(),
                    cartItem.getUnitPrice());
        }

        sql = "update t_cart_item set `count` = `count` + 1" +
                " where `book_id` = ? and `user_id` = ?";
        return update(sql, cartItem.getBookId(), cartItem.getUserId());


    }

    @Override
    public int updateCount(int itemId,int count) {
        String sql = "update t_cart_item set `count` = ? where `item_id` = ?";
        return update(sql,count,itemId);
    }

    @Override
    public int deletebook(int itemId, int userId) {
        String sql = "delete from t_cart_item where `item_id` = ? and `user_id` = ?";
        return update(sql, itemId, userId);
    }

    @Override
    public int clear(int userId) {
        String sql = "delete from t_cart_item where `user_id` = ?";
        return update(sql, userId);
    }

    @Override
    public List<CartItem> query(int userId) {
        String sql = "select `item_id` as itemid, `book_id` as bookId, `user_id` as userId, `name`,`count`" +
                ",`unit_price` as unitPrice," +
                " `unit_price` * `count` as totalPrice from t_cart_item where `user_id` = ?";

        return query(sql, userId);
    }

    @Override
    public int syncInfo(Goods goods) {
        String sql = "update t_cart_item set `name` = ? ,`unit_price` = ? where `book_id` = ?";
        return update(sql, goods.getName(), goods.getPrice(), goods.getId());
    }
}
